package org.stayfool.auth.util;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * Created by jych1 on 2016/1/1.
 */
public final class PasswordUtil {

	private static final RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
	private static final AtomicReference<String> algorithmName = new AtomicReference<String>("SHA-512");
	private static final AtomicInteger hashIterations = new AtomicInteger(2);

	private PasswordUtil() {
		// singleton
	}

	public static void setAlgorithmName(String algorithmName) {
		PasswordUtil.algorithmName.set(algorithmName);
	}

	public static void setHashIterations(int hashIterations) {
		PasswordUtil.hashIterations.set(hashIterations);
	}

	/**
	 * encrypt
	 * 
	 * @param password
	 * @param salt
	 * @return {@code String}
	 */
	public static final String encryptPassword(String password, String salt) {
		return new SimpleHash(algorithmName.get(), password, convert(salt), hashIterations.get()).toHex();
	}

	/**
	 * generate salt
	 * 
	 * @return {@code String}
	 */
	public static final String generateSalt() {
		return randomNumberGenerator.nextBytes().toHex();
	}

	/**
	 * conver {@code String} to {@code ByteSource}
	 * 
	 * @param salt
	 * @return {@code ByteSource}
	 */
	public static final ByteSource convert(String salt) {
		return ByteSource.Util.bytes(salt);
	}
}
